// 条目数量
var itemNum;

$(function () {
    // 生成工具栏
    $('#toolbar').kendoToolBar({
        resizable: false,
        items: [
            { template: '<a class="k-button k-button-icon k-state-selected" href="javascript:;" onclick="addItem();"><span class="k-icon k-i-plus"></span></a>' },
            { template: '<label class="k-checkbox-label"><input class="k-checkbox" id="selectAll" type="checkbox">全选</label>' },
            { template: '<a class="k-button k-button-icontext" href="javascript:;" onclick="batchDelete();"><span class="k-icon k-i-x"></span>批量删除</a>' }
        ]
    });
    // 获取数据源生成表单
    $.fn.ajaxPost({
        ajaxUrl: 'json/list.json',
        succeed: function (res) {
            $('#formCopy').html(kendo.template($('#editTemplate').html())(res));
            itemNum = res.data.length;
            $.each(res.data, function (i) {
                renderComponents(i + 1);
            });
        }
    });
    // 全选
    $('#selectAll').click(function () {
        if ($(this).prop('checked')) {
            $('#formCopy').find('.ids').prop('checked', true);
        } else {
            $('#formCopy').find('.ids').prop('checked', false);
        }
    });
    // 半选
    $('#formCopy').on('click', '.ids', function () {
        if ($('#formCopy').find('.ids:checked').length < $('#formCopy').find('.ids').length && $('#formCopy').find('.ids:checked').length > 0) {
            $('#selectAll').prop('checked', false).prop('indeterminate', true);
        } else if ($('#formCopy').find('.ids:checked').length === $('#formCopy').find('.ids').length) {
            $('#selectAll').prop('indeterminate', false).prop('checked', true);
        } else {
            $('#selectAll').prop('indeterminate', false).prop('checked', false);
        }
    });
    // 表单提交
    $('#submitBtn').unbind('click').click(function () {
        if ($('#formCopy').kendoValidator().data('kendoValidator').validate()) {
            var models = [];
            for (var i = 0; i < itemNum; i++) {
                if ($('#formCopy > div').length > 0) {
                    if ($('#realName' + (i + 1)).length > 0) {
                        models.push({
                            id: $('#id' + (i + 1)).val(),
                            realName: $('#realName' + (i + 1)).val(),
                            age: $('#age' + (i + 1)).data('kendoNumericTextBox').value(),
                            bloodType: $('#bloodType' + (i + 1)).data('kendoDropDownList').value(),
                            birthday: kendo.toString($('#birthday' + (i + 1)).data('kendoDatePicker').value(), 'yyyy-MM-dd'),
                            zodiac: $('#zodiac' + (i + 1)).data('kendoMultiColumnComboBox').value(),
                            constellation: $('#constellation' + (i + 1)).data('kendoMultiSelect').value()
                        });
                    }
                }
            }
            if (models.length > 0) {
                $('#loading').show();
                $.fn.ajaxPost({
                    ajaxData: {
                        models: models
                    },
                    finished: function () {
                        $('#loading').hide();
                    },
                    succeed: function () {
                        refresh();
                    },
                    isMsg: true
                });
            } else {
                alertMsg('请先增加数据项！', 'warning');
            }
        }
    });
});

// 加
function addItem() {
    itemNum++;
    $('#formCopy').append(
        '<div class="form-row border-bottom pt-2">' +
            '<div class="form-group col-xl-1">' +
                '<label class="d-none d-xl-block">&nbsp;</label>' +
                '<div class="d-flex pt-2 pt-xl-0">' +
                    '<a class="k-button k-button-icon k-del-button mx-xl-2" href="javascript:;" onclick="delItem(this);"><span class="k-icon k-i-minus"></span></a>' +
                    '<span class="k-badge k-badge-primary k-badge-pill ml-auto px-2">' + kendo.toString(itemNum, '00') + '</span>' +
                '</div>' +
            '</div>' +
            '<div class="form-group col-sm-6 col-md-4 col-xl-2">' +
                '<label class="d-block"><strong class="k-required">*</strong>姓名：</label>' +
                '<input class="k-textbox w-100" id="realName' + itemNum + '" name="realName' + itemNum + '" type="text" placeholder="文本框" required data-required-msg="请输入姓名！" pattern="[\\\u4E00-\\\u9FA5]{1,10}" data-pattern-msg="请输入1-10个汉字！">' +
            '</div>' +
            '<div class="form-group col-sm-6 col-md-4 col-xl-1">' +
                '<label class="d-block"><strong class="k-required">*</strong>年龄：</label>' +
                '<input class="w-100" id="age' + itemNum + '" name="age' + itemNum + '" type="number" placeholder="数字框" required data-required-msg="请输入年龄！">' +
                '<span class="k-invalid-msg" data-for="age' + itemNum + '"></span>' +
            '</div>' +
            '<div class="form-group col-sm-6 col-md-4 col-xl-2">' +
                '<label class="d-block"><strong class="k-required">*</strong>血型：</label>' +
                '<select class="w-100" id="bloodType' + itemNum + '" name="bloodType' + itemNum + '" required data-required-msg="请选择血型！">' +
                    '<option value="">单选下拉框</option>' +
                    '<option value="1">A 型</option>' +
                    '<option value="2">B 型</option>' +
                    '<option value="3">O 型</option>' +
                    '<option value="4">AB 型</option>' +
                    '<option value="5">其他</option>' +
                '</select>' +
                '<span class="k-invalid-msg" data-for="bloodType' + itemNum + '"></span>' +
            '</div>' +
            '<div class="form-group col-sm-6 col-md-4 col-xl-2">' +
                '<label class="d-block"><strong class="k-required">*</strong>生日：</label>' +
                '<input class="w-100" id="birthday' + itemNum + '" name="birthday' + itemNum + '" type="date" placeholder="日期框" required data-required-msg="请输入生日！">' +
                '<span class="k-invalid-msg" data-for="birthday' + itemNum + '"></span>' +
            '</div>' +
            '<div class="form-group col-sm-6 col-md-4 col-xl-1">' +
                '<label class="d-block"><strong class="k-required">*</strong>生肖：</label>' +
                '<input class="w-100" id="zodiac' + itemNum + '" name="zodiac' + itemNum + '" type="text" placeholder="表格下拉框" required data-required-msg="请选择生肖！">' +
                '<span class="k-invalid-msg" data-for="zodiac' + itemNum + '"></span><span class="k-invalid-msg" data-for="zodiac' + itemNum + '_input"></span>' +
            '</div>' +
            '<div class="form-group col-sm-6 col-md-4 col-xl-3">' +
                '<label class="d-block"><strong class="k-required">*</strong>相配的星座：</label>' +
                '<select class="w-100" id="constellation' + itemNum + '" name="constellation' + itemNum + '" multiple required data-required-msg="请选择相配的星座！">' +
                    '<option value="1">白羊座</option>' +
                    '<option value="2">金牛座</option>' +
                    '<option value="3">双子座</option>' +
                    '<option value="4">巨蟹座</option>' +
                    '<option value="5">狮子座</option>' +
                    '<option value="6">处女座</option>' +
                    '<option value="7">天秤座</option>' +
                    '<option value="8">天蝎座</option>' +
                    '<option value="9">射手座</option>' +
                    '<option value="10">山羊座</option>' +
                    '<option value="11">水瓶座</option>' +
                    '<option value="12">双鱼座</option>' +
                '</select>' +
                '<span class="k-invalid-msg" data-for="constellation' + itemNum + '"></span>' +
            '</div>' +
        '</div>'
    );
    renderComponents(itemNum);
}

// 减
function delItem(dom) {
    $(dom).closest('.form-row').remove();
}

// 渲染组件
function renderComponents(num) {
    // 年龄
    $('#age' + num).kendoNumericTextBox({
        format: 'n0',
        decimals: 0,
        min: 1,
        max: 120
    });
    // 血型
    $('#bloodType' + num).kendoDropDownList();
    // 生日
    $('#birthday' + num).kendoDatePicker({
        format: 'yyyy-MM-dd',
        footer: '今天：#= kendo.toString(data, "yyyy年MM月dd日") #',
        min: new Date(1920, 0, 1),
        max: new Date()
    });
    // 生肖
    $('#zodiac' + num).kendoMultiColumnComboBox({
        dataSource: {
            transport: {
                read: function (options) {
                    $.fn.ajaxPost({
                        ajaxUrl: 'json/zodiac.json',
                        succeed: function (res) {
                            options.success(res);
                        },
                        failed: function (res) {
                            options.error(res);
                        }
                    });
                }
            },
            schema: {
                data: 'data'
            }
        },
        dataValueField: 'zodiac',
        dataTextField: 'zodiacName',
        columns: [
            { field: 'zodiacName', title: '生肖', width: '56px' },
            { field: 'zodiacValue1', title: '年份', width: '60px' },
            { field: 'zodiacValue2', title: '年份', width: '60px' },
            { field: 'zodiacValue3', title: '年份', width: '60px' },
            { field: 'zodiacValue4', title: '年份', width: '60px' },
            { field: 'zodiacValue5', title: '年份', width: '60px' }
        ],
        filter: 'contains',
        filterFields: ['zodiacValue1', 'zodiacValue2', 'zodiacValue3', 'zodiacValue4', 'zodiacValue5'],
        minLength: 4,
        suggest: true
    });
    // 相配的星座
    $('#constellation' + num).kendoMultiSelect({
        placeholder: '多选下拉框',
        autoClose: false,
        valuePrimitive: true
    });
}

// 批量删除
function batchDelete() {
    var ids = [];
    $.each($('#formCopy .ids'), function () {
        if ($(this).prop('checked')) {
            ids.push($(this).val());
        }
    });
    if (ids.length > 0) {
        $('#loading').show();
        $.fn.ajaxPost({
            ajaxData: {
                'ids': ids
            },
            finished: function () {
                $('#loading').hide();
            },
            isMsg: true
        });
    } else {
        alertMsg('请先选择对象！', 'warning');
    }
}

// 清空
function clearForm() {
    $('#formCopy').html('');
}